from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jose import jwt, JWTError

from conf.variable import SECRET_KEY, ALGORITHM, CONTEXT_PATH
from service.user import UserModel

oauth2_scheme = OAuth2PasswordBearer(tokenUrl=CONTEXT_PATH + '/security/token')


async def get_current_user(token: str = Depends(oauth2_scheme)):
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        id: int = payload.get("id")
        username: str = payload.get("username")
        if (id is None) or (username is None):
            raise credentials_exception
        return UserModel(id=id, username=username)
    except JWTError:
        raise credentials_exception
